<template>
  <el-form class="UserAccount" label-position="top">
    <el-form-item label="手机号/登陆账号">
      <span class="fs16">{{ userInfo.phone }}</span>
      <Cbutton type="pink" size="mini" style="display: block;" @click.native="openDialog('phone')">修 改</Cbutton>
      <!-- <el-input v-model.trim="ruleForm.phone" type="number" clearable placeholder="请输入手机号" class="inputStyle" /> -->
    </el-form-item>
    <el-form-item label="绑定邮箱">
      <span class="fs16">{{ userInfo.email }}</span>
      <Cbutton type="pink" size="mini" style="display: block;" @click.native="openDialog('email')">修 改</Cbutton>
      <!-- <el-input v-model.trim="ruleForm.email" clearable placeholder="请输入绑定电子邮箱" class="inputStyle" /> -->
    </el-form-item>
    <el-form-item label="账号密码">
      <span>*********</span>
      <Cbutton type="pink" size="mini" style="display: block;" @click.native="openDialog('password')">修 改</Cbutton>
    </el-form-item>

    <Cdialog
      :visible="dialog.visible"
      :title="dialog.title"
      width="500px"
      class="Cdialog-UserAccount"
      @handleClose="handleClose"
    >
      <el-form ref="ruleForm" class="Cdialog-UserAccount-Form" :model="dialog" :rules="rules">
        <el-form-item label="邮箱地址">{{ userInfo.email | isNullData }}</el-form-item>
        <el-form-item v-if="dialog.type === 'phone'" label="手机号/登陆账号" prop="phone">
          <el-input v-model="dialog.phone" type="number" clearable placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item v-if="dialog.type === 'email'" label="新邮箱地址" prop="email">
          <el-input v-model="dialog.newEmail" clearable placeholder="请输入新邮箱地址" />
        </el-form-item>
        <el-form-item v-if="dialog.type === 'password'" label="新账号密码" prop="newPassword">
          <el-input v-model="dialog.newPassword" clearable placeholder="请输入新的账号密码" />
        </el-form-item>
        <el-form-item v-if="dialog.type === 'password'" label="确认密码" prop="password">
          <el-input v-model="dialog.password" clearable placeholder="请再次输入确认密码" />
        </el-form-item>
        <el-form-item label="邮箱验证码" prop="code">
          <el-input v-model="dialog.code" clearable placeholder="请输入邮箱验证码">
            <div slot="append" style="width: 100%;height: 100%;cursor: pointer;" @click="sendCodeValidate">{{ dialog.codeText }}</div>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" style="text-align: center;">
        <Cbutton size="small" @click.native="handleClose">取 消</Cbutton>
        <Cbutton type="pink" size="small" class="ml10" @click.native="submitForm('ruleForm')">确 定</Cbutton>
      </div>
    </Cdialog>
  </el-form>
</template>
<script>
import {
  emailVerify
} from '@/api/code'
import {
  userModifyAccount
} from '@/api/user'
import { mapGetters } from 'vuex'
export default {
  name: 'UserAccount',
  data() {
    var validatePhone = (rule, value, callback) => {
      const regPhone = /^[1][3,4,5,7,8][0-9]{9}$/ // 手机号码正则
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (value && !regPhone.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    var validateEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/ // 验证邮箱正则表达式
      if (!value) {
        callback(new Error('请输入新邮箱地址'))
      } else if (value && !regEmail.test(value)) {
        callback(new Error('请输入正确的邮箱地址'))
      } else {
        callback()
      }
    }
    var validateNewPassWord = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
      } else {
        if (this.dialog.password !== '') {
          this.$refs.ruleForm.validateField('password')
        }
        callback()
      }
    }
    var validatePassWord = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.dialog.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      dialog: {
        visible: false,
        title: '',
        type: '', // 对话框类型

        phone: '', // 手机号/登陆账号
        email: '', // 邮箱地址
        newEmail: '', // 新邮箱地址
        newPassword: '', // 新密码
        password: '', // 确认密码
        code: '', // 验证码

        timer: '', // 验证定时器
        codeText: '获取验证码' // 验证d码文本显示
      },
      rules: {
        phone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        email: [{ required: true, validator: validateEmail, trigger: 'blur' }],
        newPassword: [{ validator: validateNewPassWord, trigger: 'blur' }],
        password: [{ validator: validatePassWord, trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }, { min: 4, max: 4, message: '请输入4位验证码', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    logout() {
      this.$store.dispatch('user/logout').then(() => {
        this.$router.push(`/login?redirect=${this.$route.fullPath}`)
      })
    },
    // 修改账户接口
    async modifyAccount() {
      const res = await userModifyAccount(this.dialog)
      if (res.code === 0) {
        switch (this.dialog.type) {
          case 'phone': // 修改了账号需要重新登录
            this.handleClose()
            this.$message.success('修改账号成功，请退出重新登陆')
            this.logout()
            break
          case 'password': // 修改了密码需要重新登录
            this.handleClose()
            this.$message.success('重置密码成功，请退出重新登陆')
            this.logout()
            break
          default: // 关闭对话框，更新信息
            this.handleClose()
            this.$message.success(res.msg)
            this.$store.dispatch('user/getInfo')
            break
        }
      }
    },
    // 提交校验
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.modifyAccount()
        } else {
          return false
        }
      })
    },
    // 格式化时间
    formatDate(ss) {
      let min = 0
      let result = ''
      if (ss > 60) { // 如果秒数大于60，将秒数转换成整数
        min = parseInt(ss / 60)// 获取分钟，除以60取整数，得到整数分钟
        ss = parseInt(ss % 60)// 获取秒数，秒数取佘，得到整数秒数
      }
      result = `${min.toString().padStart(2, '0')} : ${ss.toString().padStart(2, '0')}`
      return result
    },
    // 设置计时器
    setCodeTimer() {
      let ss = 300 // 5分钟
      this.dialog.timer = setInterval(() => {
        ss--
        this.dialog.codeText = this.formatDate(ss)
        if (ss === 0) { // 计时器结束
          this.dialog.codeText = '重新发送'
          clearInterval(this.dialog.timer)
        }
      }, 1000)
    },
    // 发送验证码
    async sendCode(email) {
      if (this.dialog.timer) { // 验证码已发送后不能再发
        return
      }
      const res = await emailVerify({ email })
      if (res.code === 0) {
        this.$message.success(res.msg)
        this.setCodeTimer() // 设置定时器
      }
    },
    // 发送验证码校验
    sendCodeValidate() {
      // 根据类型校验不同的单项
      this.$refs.ruleForm.validateField(this.dialog.type, error => {
        if (!error) {
          this.sendCode(this.userInfo.email) // 直接发送该账号验证码
        }
      })
    },
    // 关闭弹窗
    handleClose() {
      this.dialog = {
        visible: false,
        title: '',
        type: '',

        phone: '', // 手机号/登陆账号
        email: '', // 邮箱地址
        code: '', // 验证码
        timer: '', // 验证定时器
        codeText: '获取验证码' // 验证码文本显示
      }
    },
    // 打开弹窗
    openDialog(type) {
      switch (type) {
        case 'phone': // 修改手机号
          this.dialog.title = '修改手机号/登录账号'
          break
        case 'email': // 修改邮箱
          this.dialog.title = '修改绑定邮箱'
          break
        case 'password': // 重置密码
          this.dialog.title = '重置密码'
          break
      }
      this.dialog.phone = this.userInfo.phone
      this.dialog.email = this.userInfo.email
      this.dialog.type = type
      this.dialog.visible = true
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-bottom: 10px;
}
.inputStyle{
  width: 400px;
  max-width: 100%;
}
.Cdialog-UserAccount{
  &-Form{
    padding: 10px 20px;
  }
}
</style>
